package com.wolfking.service.ssoauth.resource;

import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wolfking.back.core.bean.Menu;
import com.wolfking.back.core.bean.User;
import com.wolfking.back.core.exception.ExceptionCode;
import com.wolfking.back.core.util.PasswordUtil;
import com.wolfking.back.core.util.ResponseUtil;
import com.wolfking.service.ssoauth.service.CacheService;
import com.wolfking.service.ssoauth.service.MenuService;
import com.wolfking.service.ssoauth.service.UserService;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

import jersey.repackaged.com.google.common.collect.Lists;
import jersey.repackaged.com.google.common.collect.Sets;

@Component
@Path("/sso")
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "/sso", description = "sso单点登录", produces = MediaType.APPLICATION_JSON)
public class SsoResource {

	@Autowired
	private UserService userService;

	@Autowired
	private CacheService cacheService;

	@Autowired
	private MenuService menuService;

	@GET
	@Path("/{username}/{password}")
	@ApiOperation(value = "用户登录接口", httpMethod = "GET", notes = "用户登录接口", response = User.class)
	public Response userLogin(
			@PathParam("username") @ApiParam(required = true, name = "username", value = "用户名") String username,
			@PathParam("password") @ApiParam(required = true, name = "password", value = "密码") String password) {
		User user = new User();
		user.setLoginName(username);
		List<User> list = userService.seleteAccuracy(user);
		if (list == null || list.size() == 0)
			return ResponseUtil.exceptionResponse(ExceptionCode.BIZ_ERROR_USER_NOT_EXIST);
		user = list.get(0);
		if ("1".equals(user.getDelFlag()))
			return ResponseUtil.exceptionResponse(ExceptionCode.BIZ_ERROR_USER_NOT_AVAILABLE);
		if (!PasswordUtil.validatePassword(password, user.getPassword()))
			return ResponseUtil.exceptionResponse(ExceptionCode.BIZ_ERROR_USER_COUNT_NAME_NOMATHCH);
		String tokenId = UUID.randomUUID().toString().replaceAll("-", "");
		user.setTokenId(tokenId);
		cacheService.saveToken(user);
		return ResponseUtil.okResponse(user);
	}

	@GET
	@Path("/checklogin/{tokenId}")
	@ApiOperation(value = "校验用户登录接口", httpMethod = "GET", notes = "校验用户登录接口", response = User.class)
	public Response checkLogin(
			@PathParam("tokenId") @ApiParam(required = true, name = "tokenId", value = "客户端缓存的token") String tokenId) {
		User user = cacheService.getTokenUser(tokenId);
		return ResponseUtil.okResponse(user);
	}

	@GET
	@Path("/logout{tokenId}")
	@ApiOperation(value = "用户注销接口", httpMethod = "GET", notes = "用户注销接口", response = Boolean.class)
	public Response logout(
			@PathParam("tokenId") @ApiParam(required = true, name = "tokenId", value = "客户端缓存的token") String tokenId) {
		cacheService.clearToken(tokenId);
		return ResponseUtil.okResponse(true);
	}

	@GET
	@Path("/{userId}/authCodes")
	@ApiOperation(value = "获取用户所有的鉴权码", httpMethod = "GET", notes = "获取用户所有的鉴权码", response = String.class, responseContainer = "Set")
	public Response getUserAuthCodes(@PathParam("userId") String userId) {
		Set<String> set = Sets.newHashSet();
		List<String> list = userService.getUserAllAuthCodes(userId);
		if (list != null)
			set.addAll(list);
		return ResponseUtil.okResponse(set);
	}

	@GET
	@Path("/{userId}/menus")
	@ApiOperation(value = "获取用户所有的菜单", httpMethod = "GET", notes = "获取用户所有的鉴菜单", response = Menu.class, responseContainer = "List")
	public Response getUserMenus(@PathParam("userId") String userId) {
		List<String> menuIds = userService.getUserMenuIds(userId);
		if (menuIds == null || menuIds.size() == 0)
			return ResponseUtil.okResponse(Lists.newArrayList());
		else {
			StringBuilder sb = new StringBuilder();
			for (String id : menuIds)
				sb.append(",").append(id);
			sb.setCharAt(0, ' ');
			return ResponseUtil.okResponse(menuService.selectByIds(sb.toString().trim()));
		}

	}

}
